﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SPCFMedicineInformer.Helpers;
using System.Text;
using SPCFMedicineInformer.Constants;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.web;
using umbraco.NodeFactory;
using Vega.USiteBuilder;
using SPCFMedicineInformer.DocumentTypes;
using umbraco;

namespace SPCFMedicineInformer.Masterpages
{
    public partial class Admin_Abbreviation_Detail : System.Web.UI.MasterPage
    {
        static int id = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            int tempInt;
            id = Request.QueryString["id"] != null ? int.TryParse(Request.QueryString["id"].ToString(), out tempInt) ? tempInt : 1 : 0;
            bool isNew = Request.QueryString["n"] != null ? Request.QueryString["n"].ToString() == "1" ? true : false : false;
            btnDelete.Visible = id > 0 ? true : false;
            if (!IsPostBack)
            {
       
                if (id > 0)
                {
                    var node = new Node(id);
                    var doc = node != null && node.NodeTypeAlias == "AbbreviationItem" ? ContentHelper.GetByNodeId<AbbreviationItem>(id) : null;
                    if (doc != null)
                    {
                        txtAbbreviation.Text = doc.Abbreviation;
                        txtMeaning.Text = doc.Meaning;
                        ShowContent(true);
                        if (isNew)
                            FormHelper.ShowMessage(MessageType.Done, "Abbreviation Succesfully Saved!", MsgLiteral);
                    }
                    else
                        ShowContent(false);
                }

            }
        }

        void ShowContent(bool b)
        {
            plcContent.Visible = b;
            plcError.Visible = !b;
        }
        void Update()
        {
            if (id > 0)
            {
                var d = new Document(id);
                if (d != null)
                {
                    TransferDetailsToUmbraco(d);
                }
            }
        }
        int AddNew()
        {
            DocumentType UmbracoDocType = DocumentType.GetByAlias("AbbreviationItem");
            var parentId = NodeLocator.GetNodeOfExactType<AbbreviationFolder>().Id;
            if (parentId > 0)
            {
                Document d = Document.MakeNew(string.Concat(StringUtils.TruncateIfLonger(txtAbbreviation.Text, 100), "-", StringUtils.TruncateIfLonger(txtMeaning.Text, 150)), UmbracoDocType, User.GetUser(0), parentId);
                TransferDetailsToUmbraco(d);
                return d.Id;
            }
            return 0;
        }
        void TransferDetailsToUmbraco(Document d)
        {
            d.Text = string.Concat(StringUtils.TruncateIfLonger(txtAbbreviation.Text, 100), "-", StringUtils.TruncateIfLonger(txtMeaning.Text, 150));
            d.getProperty(UmbracoPropertyName.ABBREVIATION).Value = txtAbbreviation.Text;
            d.getProperty(UmbracoPropertyName.MEANING).Value = txtMeaning.Text;
            d.Publish(User.GetUser(0));
            umbraco.library.UpdateDocumentCache(d.Id);
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (IsValidate())
            {
                if (id > 0)
                {
                    Update();
                    FormHelper.ShowMessage(MessageType.Done, "Abbreviation Succesfully Saved!", MsgLiteral);
                }
                else
                {
                    id = AddNew();
                    Response.Redirect("/admin/utilities/abbreviations/abbreviation-entry.aspx?id=" + id + "&n=1");
                }
            }
        }
        bool IsValidate()
        {
            bool result = true;
            
            var sb = new StringBuilder();
            var msgFormat = "<p class=\"{0}\">{1}</p>";
            if (string.IsNullOrWhiteSpace(txtAbbreviation.Text))
            {
                result = false;
                sb.AppendLine(string.Format(msgFormat, "msg warning", "Abbreviation is required!"));
            }
            if (string.IsNullOrEmpty(txtMeaning.Text))
            {
                result = false;
                sb.AppendLine(string.Format(msgFormat, "msg warning", "Meaning is required!"));
            }
            if (!result)
            {
                MsgLiteral.Visible = true;
                MsgLiteral.Text = sb.ToString();
            }
            return result;
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("/admin/utilities/abbreviations");
        }      
        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            Response.Redirect("/admin/utilities/abbreviations/abbreviation-entry.aspx");
        }
        protected void btnSaveAndClear_Click(object sender, EventArgs e)
        {
            if (IsValidate())
            {
                if (id > 0)
                {
                    Update();
                    Response.Redirect("/admin/utilities/abbreviations/abbreviation-entry.aspx");
                }
                else
                {
                    id = AddNew();
                    Response.Redirect("/admin/utilities/abbreviations/abbreviation-entry.aspx");
                }
            }
        }
        void Delete(int id)
        {
            if (id > 0)
            {
                Document doc = new Document(id);
                if (doc.Published)
                {
                    doc.UnPublish();
                    library.UnPublishSingleNode(doc.Id);
                }
                doc.delete();
                Response.Redirect("/admin/utilities/abbreviations");
            }
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            Delete(id);
        }
    }
}